import {Component, OnDestroy} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {OAuthModule, OAuthService} from "angular-oauth2-oidc";
import {authConfig} from "./auth.config";
import {HttpClientModule} from "@angular/common/http";
import {AuthService} from "./service/auth.service";
import {Subscription} from "rxjs";
import {HeaderComponent} from "./components/ui/header/header.component";
import {FooterComponent} from "./components/ui/footer/footer.component";
import {Router} from "@angular/router";


@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    HttpClientModule,
    HeaderComponent,
    FooterComponent,
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent implements OnDestroy{
  title = 'els-client'
  text = ''
  helloSubscription: Subscription | undefined

  constructor(private oauthService: OAuthService,
              private authService: AuthService,
              private router: Router

  ) {
    this.configure()
    OAuthModule
    .forRoot( {
      resourceServer: {
        allowedUrls: ['http://localhost:8189/api/v1/auth',
          'http://localhost:8189/api/v1/emergency'],
        sendAccessToken: true
      }
    })
  }

  private configure() {
    this.oauthService.configure(authConfig)
    this.oauthService.setupAutomaticSilentRefresh()
    this.oauthService.loadDiscoveryDocumentAndTryLogin().then(r =>//TRY login!!!
    console.log(r + ' Enter'))
  }

  getData() {
    this.helloSubscription = this.authService.getUser().subscribe(response => {
      this.text= response
    })

  }

  login() {
    this.oauthService.initCodeFlow()
    console.log('login метод вызван')
    this.router.navigate(['/cabinet'])
  }

  logout() {
    this.oauthService.logOut()
  }

  ngOnDestroy(): void {
    // @ts-ignore
    this.helloSubscription.unsubscribe()
  }
}
